package com.yff.tuan.controller;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.yff.tuan.model.Broken;
import com.yff.tuan.model.BrokenCheck;
import com.yff.tuan.model.BrokenExample;
import com.yff.tuan.model.BrokenProblemExample;
import com.yff.tuan.model.CustomerExample;
import com.yff.tuan.model.Track;
import com.yff.tuan.model.TreadExample;
import com.yff.tuan.service.BrokenService;
import com.yff.tuan.service.CustomerService;
import com.yff.tuan.service.TreadService;
import com.yff.tuan.util.DateUtil;
import com.yff.tuan.util.ImageUtil;
import com.yff.tuan.util.MathUtil;
import com.yff.tuan.util.ObjectUtils;
import com.yff.tuan.util.Page;
import com.yff.tuan.util.WordUtils;
import com.yff.tuan.vo.BrokenExport;
import com.yff.tuan.vo.BrokenObject;
import com.yff.tuan.vo.BrokenObjectCheck;

@Controller
@RequestMapping("/broken")
public class BrokenController {
	@Autowired BrokenService brokenService;
	@Autowired CustomerService customerService;
	@Autowired TreadService treadService;
	
	@RequestMapping("/list")
	public String query(Model model,Integer pageNum,HttpServletRequest request,HttpServletResponse response) {
		Page<Broken> page = brokenService.queryByPage(new BrokenExample(), null == pageNum ? 1 : pageNum);
		model.addAttribute("page", page);
		model.addAttribute("customers", customerService.query(new CustomerExample()));
		return "/broken_list";
	}
	
	@ResponseBody
	@RequestMapping("/wxlist")
	public Object wxlist(Model model,HttpServletRequest request,HttpServletResponse response) {
		List<Broken> brokens =  brokenService.queryforwx();
		for(Broken broken:brokens){
			if(broken.getCheckDate() != null){
				broken.setCheckDateStr(DateUtil.getFormatDate(broken.getCheckDate(), DateUtil.FORMAT_YYMMDD));
			}else{
				broken.setCheckDateStr("");
			}
		}
		return brokens;
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Object add(Model model,@RequestBody Broken broken,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> map = new HashMap<String,Object>();
		broken.setCheckDate(new Date());
		int i = brokenService.insert(broken);
		map.put("add", i>0?true:false);
		return map;
	}
	
	@RequestMapping("/brokenChecks")
	public String detail(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		
		List<BrokenCheck> brokenChecks = brokenService.queryByBrokenId(id);
		if(null != brokenChecks) {
			model.addAttribute("id", id);
			model.addAttribute("brokenChecks", brokenChecks);
			model.addAttribute("treads", treadService.query(new TreadExample()));
			model.addAttribute("tyreSizes", customerService.queryTyreSize());
			model.addAttribute("brands", customerService.queryBrand());
			model.addAttribute("problems", brokenService.queryBrokenProblem(new BrokenProblemExample()));
		}
		return "/broken_check";
	}
	
	@RequestMapping("/wxdetail")
	@ResponseBody
	public Object wxdetail(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		List<BrokenCheck> brokenChecks = brokenService.queryByBrokenId(id);
		for(BrokenCheck brokenCheck:brokenChecks){
			if(null != brokenCheck.getUpdateTime()){
				brokenCheck.setUpdateTimeStr(DateUtil.getFormatDate(brokenCheck.getUpdateTime(), DateUtil.FORMAT_YYMMDD));
			}else{
				brokenCheck.setUpdateTimeStr("");
			}
		}
		return brokenChecks;
	}
	
	@RequestMapping("/toAddCheck")
	public Object toAddCheck(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		model.addAttribute("id", id);
		model.addAttribute("treads", treadService.query(new TreadExample()));
		model.addAttribute("tyreSizes", customerService.queryTyreSize());
		model.addAttribute("brands", customerService.queryBrand());
		model.addAttribute("problems", brokenService.queryBrokenProblem(new BrokenProblemExample()));
		return "/broken_check_add";
	}
	
	@RequestMapping("/addCheck")
	@ResponseBody
	public Object addCheck(Model model,BrokenCheck brokenCheck,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> map = new HashMap<String,Object>();
		brokenCheck.setUpdateTime(new Date());
		int i = brokenService.insertBrokenCheck(brokenCheck);
		map.put("add", i>0?true:false);
		return map;
	}
	
	@RequestMapping("/brokenCheckDetail")
	public String brokenCheckDetail(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		
		BrokenCheck brokenCheck = brokenService.findByPrimaryKey(id);
		if(null != brokenCheck) {
			model.addAttribute("brokenCheck", brokenCheck);
		}
		return "/broken_detail";
	}
	
	@RequestMapping("/wxcheck")
	@ResponseBody
	public Object wxcheck(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		BrokenCheck brokenCheck = brokenService.findByPrimaryKey(id);
		if(null != brokenCheck.getUpdateTime()){
			brokenCheck.setUpdateTimeStr(DateUtil.getFormatDate(brokenCheck.getUpdateTime(), DateUtil.FORMAT_YYMMDD));
		}else{
			brokenCheck.setUpdateTimeStr("");
		}
		return brokenCheck;
	}
	
	@RequestMapping("/exportBroken")
	public String exportBroken(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		model.addAttribute("id", id);
		return "/broken_export";
	}
	
	@RequestMapping("/export")
	public void export(Model model,@RequestParam("id") Integer id,
			@RequestParam("file1") CommonsMultipartFile[] file1,
			@RequestParam("comment1") String comment1,
			@RequestParam("file2") CommonsMultipartFile[] file2,
			@RequestParam("comment2") String comment2,
			@RequestParam("file3") CommonsMultipartFile[] file3,
			@RequestParam("comment3") String comment3,
			@RequestParam("file4") CommonsMultipartFile[] file4,
			@RequestParam("comment4") String comment4,
			HttpServletRequest request,HttpServletResponse response) throws Exception{
		String image1 = "",image2="";
		if(null != file1 && file1.length>0) {
			image1 = file1.length>0?ImageUtil.getImageStr(file1[0].getInputStream()):"";  
			image2 = file1.length>1?ImageUtil.getImageStr(file1[1].getInputStream()):"";  
		}
		String image3 = "",image4="";
		if(null != file2 && file2.length>0) {
			image3 = file2.length>0?ImageUtil.getImageStr(file2[0].getInputStream()):"";  
			image4 = file2.length>1?ImageUtil.getImageStr(file2[1].getInputStream()):"";  
		}
		String image5 = "",image6="";
		if(null != file3 && file3.length>0) {
			image5 = file3.length>0?ImageUtil.getImageStr(file3[0].getInputStream()):"";  
			image6 = file3.length>1?ImageUtil.getImageStr(file3[1].getInputStream()):"";  
		}
		String image7 = "",image8="";
		if(null != file4 && file4.length>0) {
			image7 = file4.length>0?ImageUtil.getImageStr(file4[0].getInputStream()):"";  
			image8 = file4.length>1?ImageUtil.getImageStr(file4[1].getInputStream()):"";  
		}
		Broken brokenFind = new Broken();
		brokenFind.setId(id);
		Broken broken = brokenService.find(brokenFind);
		
		List<BrokenObjectCheck> useProblem = brokenService.queryProblem(broken.getId(), "use_problem_id");
		List<BrokenObjectCheck> tireProblem = brokenService.queryProblem(broken.getId(), "tire_problem_id");
		List<BrokenObjectCheck> manageProblem = brokenService.queryProblem(broken.getId(), "manage_problem_id");
		List<BrokenObjectCheck> repairProblem = brokenService.queryProblem(broken.getId(), "repair_problem_id");
		List<BrokenObjectCheck> retreadProblem = brokenService.queryProblem(broken.getId(), "retread__problem_id");
		
		
		int useProblemCount = 0,tireProblemCount = 0,manageProblemCount = 0, repairProblemCount = 0, retreadProblemCount = 0;
		for(BrokenObjectCheck check:useProblem){
			useProblemCount += check.getCount();
		}
		for(BrokenObjectCheck check:tireProblem){
			tireProblemCount += check.getCount();
		}
		for(BrokenObjectCheck check:manageProblem){
			manageProblemCount += check.getCount();
		}
		for(BrokenObjectCheck check:repairProblem){
			repairProblemCount += check.getCount();
		}
		for(BrokenObjectCheck check:retreadProblem){
			retreadProblemCount += check.getCount();
		}
		int problemCount = useProblemCount+tireProblemCount+manageProblemCount +repairProblemCount +retreadProblemCount;
		
		
		List<BrokenObject> problems = new ArrayList<BrokenObject>();
		if(!useProblem.isEmpty()){
			BrokenObject useProblemObject = new BrokenObject();
			for(BrokenObjectCheck check:useProblem){
				check.setRate(String.valueOf(MathUtil.parseDouble(check.getCount()*100/problemCount)));
			}
			useProblemObject.setChecks(useProblem);
			useProblemObject.setName("轮胎使用问题");
			useProblemObject.setCount(String.valueOf(useProblemCount));
			useProblemObject.setRate(String.valueOf(MathUtil.parseDouble(useProblemCount*100/problemCount)));
			problems.add(useProblemObject);
		}
		if(!tireProblem.isEmpty()){
			BrokenObject tireProblemObject = new BrokenObject();
			for(BrokenObjectCheck check:tireProblem){
				check.setRate(String.valueOf(MathUtil.parseDouble(check.getCount()*100/problemCount)));
			}
			tireProblemObject.setChecks(tireProblem);
			tireProblemObject.setName("胎体问题");
			tireProblemObject.setCount(String.valueOf(useProblemCount));
			tireProblemObject.setRate(String.valueOf(MathUtil.parseDouble(useProblemCount*100/problemCount)));
			problems.add(tireProblemObject);
		}
		if(!manageProblem.isEmpty()){
			BrokenObject manageProblemObject = new BrokenObject();
			for(BrokenObjectCheck check:manageProblem){
				check.setRate(String.valueOf(MathUtil.parseDouble(check.getCount()*100/problemCount)));
			}
			manageProblemObject.setChecks(manageProblem);
			manageProblemObject.setName("管理规程问题");
			manageProblemObject.setCount(String.valueOf(useProblemCount));
			manageProblemObject.setRate(String.valueOf(MathUtil.parseDouble(useProblemCount*100/problemCount)));
			problems.add(manageProblemObject);
		}
		if(!repairProblem.isEmpty()){
			BrokenObject repairProblemObject = new BrokenObject();
			for(BrokenObjectCheck check:repairProblem){
				check.setRate(String.valueOf(MathUtil.parseDouble(check.getCount()*100/problemCount)));
			}
			repairProblemObject.setChecks(repairProblem);
			repairProblemObject.setName("修补问题");
			repairProblemObject.setCount(String.valueOf(useProblemCount));
			repairProblemObject.setRate(String.valueOf(MathUtil.parseDouble(useProblemCount*100/problemCount)));
			problems.add(repairProblemObject);
		}
		if(!retreadProblem.isEmpty()){
			BrokenObject retreadProblemObject = new BrokenObject();
			for(BrokenObjectCheck check:retreadProblem){
				check.setRate(String.valueOf(MathUtil.parseDouble(check.getCount()*100/problemCount)));
			}
			retreadProblemObject.setChecks(retreadProblem);
			retreadProblemObject.setName("翻新问题");
			retreadProblemObject.setCount(String.valueOf(useProblemCount));
			retreadProblemObject.setRate(String.valueOf(MathUtil.parseDouble(useProblemCount*100/problemCount)));
			problems.add(retreadProblemObject);
		}
		BrokenExport export = new BrokenExport();
		
		export.setCustomerName(broken.getCustomerName());
		export.setCreateTime(DateUtil.getFormatDate(broken.getCheckDate(), DateUtil.FORMAT_YYMMDDHHMMSS));
		export.setImage1(image1);
		export.setImage2(image2);
		export.setImage3(image3);
		export.setImage4(image4);
		export.setImage5(image5);
		export.setImage6(image6);
		export.setImage7(image7);
		export.setImage8(image8);
		
		export.setComment1(comment1);
		export.setComment2(comment2);
		export.setComment3(comment3);
		export.setComment4(comment4);
		
		export.setProblemCount(problemCount);
		export.setProblems(problems);
		
		List<BrokenCheck> brokenCheckes = brokenService.queryByBrokenId(broken.getId());
		int rCount = 0;
		int xCount = 0;
		int tread02Count=0;
		int tread35Count=0;
		int tread60Count=0;
		int tread11Count=0;
		
		for(BrokenCheck check:brokenCheckes){
			if(check.getrX() !=null && check.getrX()==0){
				rCount ++;
			}
			if(check.getrX() !=null && check.getrX()==1){
				xCount ++;
			}
			double big = getBig(check.getRemainTreadDeep1(), check.getRemainTreadDeep2(), check.getRemainTreadDeep3());
			if(big<=2){
				tread02Count++;
			}
			if(big<5){
				tread35Count++;
			}
			if(big<=10){
				tread60Count++;
			}
			if(big>10){
				tread11Count++;
			}
		}
		int rxCount = rCount+xCount;
		
		export.setTread02Count(tread02Count);
		export.setTread35Count(tread35Count);
		export.setTread60Count(tread60Count);
		export.setTread11Count(tread11Count);
		int treadTotal = tread02Count+tread35Count+tread60Count+tread11Count;
		export.setTread02Rate(MathUtil.parseDouble(tread02Count*100/treadTotal));
		export.setTread35Rate(MathUtil.parseDouble(tread35Count*100/treadTotal));
		export.setTread60Rate(MathUtil.parseDouble(tread60Count*100/treadTotal));
		export.setTread11Rate(MathUtil.parseDouble(tread11Count*100/treadTotal));
		
		List<BrokenObjectCheck> tyreSizes = brokenService.queryTyreSize(broken.getId());
		int totalTyreSize = 0;
		for(BrokenObjectCheck check:tyreSizes){
			totalTyreSize += check.getCount();
		}
		for(BrokenObjectCheck check:tyreSizes){
			check.setRate(String.valueOf(MathUtil.parseDouble(check.getCount()*100/totalTyreSize)));
		}
		export.setTyreSizes(tyreSizes);
		
		List<BrokenObjectCheck> brands = brokenService.queryBrand(broken.getId());
		int totalBrands = 0;
		for(BrokenObjectCheck check:brands){
			totalBrands += check.getCount();
		}
		for(BrokenObjectCheck check:brands){
			check.setRate(String.valueOf(MathUtil.parseDouble(check.getCount()*100/totalBrands)));
		}
		export.setBrands(brands);
		
		export.setrCount(rCount);
		export.setrRate(MathUtil.parseDouble(rCount*100/rxCount));
		export.setxCount(xCount);
		export.setxRate(MathUtil.parseDouble(xCount*100/rxCount));
		
		
		Map<String, Object> map = new HashMap<String,Object>();  
        map.put("b", ObjectUtils.objectToMap(export));
        WordUtils.exportMillCertificateWord(request,response,map,"broken.ftl","破损分析"); 
	}
	
	/*@RequestMapping("/check")
	public String check(Model model,Integer id,HttpServletRequest request,HttpServletResponse response){
		
		TrackTire trackTire = brokenService.findTrackTireByPrimaryKey(id);
		if(null != trackTire) {
			model.addAttribute("trackTire", trackTire);
		}
		return "/track_tire";
	}*/
	
	private double getBig(double a ,double b ,double c){
		double num = a;
		num = a<b?b:a;
		num = num<c?c:num;
		return num;
	}
}
